#ifndef UI_FUNCS_HPP
#define UI_FUNCS_HPP

#include <Arduino.h>
#include <lvgl.h>

#include "ui/src/ui_events.h"
#include "ui/ui.h"
#include "dev/stepper.hpp"
#include "macro.hpp"


u_int16_t findIndexByValue(u_int16_t value, u_int16_t* lst, u_int16_t size) {
    for (int i = 0; i < size; i++) {
        if (lst[i] == value) {
            return i;
        }
    }
    return 0; // 未找到
}

u_int16_t ms_table[] = {1,2,4,8,16,32,64,128,256};
float sa_table[] = {0.9, 1.8};
// 从文件中加载参数，并更新UI中的显示
void ui_init_params(){
    lv_dropdown_set_selected(ui_DropdownM1MicroSteps, 
        findIndexByValue(stepper_x.microstepping, ms_table, 9));
    lv_dropdown_set_selected(ui_DropdownM2MicroSteps, 
        findIndexByValue(stepper_y.microstepping, ms_table, 9));
    lv_textarea_set_text(ui_TextAreaMacro, get_macro_content().c_str());
    lv_bar_set_value(ui_BarMacro, 0, LV_ANIM_OFF);
}

// =========================数字输入键盘====================================

lv_obj_t * NUM_TARGET_TextArea = NULL;
char num_key_token = '+';
void TextAreaInsert(char c){
    lv_textarea_add_char(ui_TextAreaKeyNum, c);
}

void func_key7(lv_event_t * e){
    TextAreaInsert('7');
}
void func_key8(lv_event_t * e){
    TextAreaInsert('8');
}
void func_key9(lv_event_t * e){
    TextAreaInsert('9');
}
void func_key_clear(lv_event_t * e){
    lv_textarea_set_text(ui_TextAreaKeyNum, "");
}
void func_key4(lv_event_t * e){
    TextAreaInsert('4');
}
void func_key5(lv_event_t * e){
    TextAreaInsert('5');
}
void func_key6(lv_event_t * e){
    TextAreaInsert('6');
}
void func_key_del(lv_event_t * e){
    lv_textarea_del_char(ui_TextAreaKeyNum);
}
void func_key1(lv_event_t * e){
    TextAreaInsert('1');
}
void func_key2(lv_event_t * e){
    TextAreaInsert('2');
}
void func_key3(lv_event_t * e){
    TextAreaInsert('3');
}

void func_key_minus(lv_event_t * e){
    if (!(NUM_TARGET_TextArea == ui_TextAreaM1Start \
        || NUM_TARGET_TextArea == ui_TextAreaM2Start)) {return;}
    if (num_key_token == '+') {
        num_key_token = '-';
        lv_label_set_text(ui_Label44, "-");
    } else {    
        num_key_token = '+';
        lv_label_set_text(ui_Label44, "+");
    }
}

void func_key_enter(lv_event_t * e){
    const char *text = lv_textarea_get_text(ui_TextAreaKeyNum);
    if (NUM_TARGET_TextArea == NULL) {return;}
    // logf("[UI] Tok %c, Text %s", num_key_token, text);
    if (NUM_TARGET_TextArea == ui_TextAreaM1Start || NUM_TARGET_TextArea == ui_TextAreaM1Start){
        // 给text的前面设置正负号
        String newText = String(num_key_token) + String(text);
        if (num_key_token == '-') {
            // logf("[UI] Tok %c, newText %s", num_key_token, newText.c_str());
            lv_textarea_set_text(NUM_TARGET_TextArea, newText.c_str());
            _ui_screen_change(&ui_Screen1, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0, &ui_Screen1_screen_init);
            return;
        }
    }
    lv_textarea_set_text(NUM_TARGET_TextArea, text);
    _ui_screen_change(&ui_Screen1, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0, &ui_Screen1_screen_init);
}
void func_key0(lv_event_t * e){
    TextAreaInsert('0');
}
void func_key_comma(lv_event_t * e){
    const char *text = lv_textarea_get_text(ui_TextAreaKeyNum);
    // 如果里面没有小数点，就插入小数点
    if (strchr(text, '.') == NULL) {
        TextAreaInsert('.');
    }
}
// =========================数字输入文本框的点选============================

void func_textAreaM1SpeedClicked(lv_event_t * e){
    NUM_TARGET_TextArea = ui_TextAreaM1Speed;
    lv_textarea_set_text(ui_TextAreaKeyNum, "");
    lv_label_set_text(ui_Label44, "+");
}

void func_textAreaM2SpeedClicked(lv_event_t * e){
    NUM_TARGET_TextArea = ui_TextAreaM2Speed;
    lv_textarea_set_text(ui_TextAreaKeyNum, "");
    lv_label_set_text(ui_Label44, "+");
    
}

void func_TextAreaM1StartClicked(lv_event_t * e){
    NUM_TARGET_TextArea = ui_TextAreaM1Start;
    lv_textarea_set_text(ui_TextAreaKeyNum, "");
    lv_label_set_text(ui_Label44, "+");
    num_key_token = '+';
}

void func_TextAreaM2StartClicked(lv_event_t * e){
    NUM_TARGET_TextArea = ui_TextAreaM2Start;
    lv_textarea_set_text(ui_TextAreaKeyNum, "");
    lv_label_set_text(ui_Label44, "+");
    num_key_token = '+';
}

// =========================宏命令输入框====================================
void funcMacroTextAreaClicked(lv_event_t * e){
    const char *text = lv_textarea_get_text(ui_TextAreaMacro);
    lv_textarea_set_text(ui_TextAreaKey, text);  
}

void func_macro_start_cb(lv_event_t * e){
    static bool is_started = false;
    if (!is_started){
        if( get_macro_lenght() == 0) {return;}
        lv_obj_set_style_bg_color(ui_btnMacroStart, lv_color_hex(0xE60B0B), LV_PART_MAIN | LV_STATE_DEFAULT);
        lv_label_set_text(ui_Label7, "Stop");
        start_macro();
        is_started = true;
    }else{
        lv_obj_set_style_bg_color(ui_btnMacroStart, lv_color_hex(0x0D8723), LV_PART_MAIN | LV_STATE_DEFAULT);
        lv_label_set_text(ui_Label7, "Start");
        stop_macro();
        
        is_started = false;
    }
}

void func_macro_key_ready_btn(lv_event_t * e){
    const char *text = lv_textarea_get_text(ui_TextAreaKey);
    lv_textarea_set_text(ui_TextAreaMacro, text);
    save_macro(String(text));
}

// =========================步进电机按钮====================================
void func_M1SpeedUnitChanged(lv_event_t * e){
    static float r_spd = 0;
    static int   f_spd = 0;
    static uint8_t last_index = 0;
    if (lv_dropdown_get_selected(ui_DropdownM1SpeedType)==0){
        // Hz
        if (last_index==0) {return;}
        last_index = 0;
        r_spd = String(lv_textarea_get_text(ui_TextAreaM1Speed)).toFloat();
        f_spd = stepper_x.rps_to_pulse_freq(r_spd);
        lv_textarea_set_text(ui_TextAreaM1Speed, String(f_spd).c_str());
    }else{
        // r/s
        if (last_index==1) {return;}
        last_index = 1;
        f_spd = String(lv_textarea_get_text(ui_TextAreaM1Speed)).toInt();
        r_spd = stepper_x.pulse_freq_to_rps(f_spd);
        lv_textarea_set_text(ui_TextAreaM1Speed, String(r_spd).c_str());
    }
}

void func_M2SpeedUnitChanged(lv_event_t * e){
    static float r_spd = 0;
    static int   f_spd = 0;
    static uint8_t last_index = 0;
    if (lv_dropdown_get_selected(ui_DropdownM2SpeedType)==0){
        // Hz
        if (last_index==0) {return;}
        last_index = 0;
        r_spd = String(lv_textarea_get_text(ui_TextAreaM2Speed)).toFloat();
        f_spd = stepper_y.rps_to_pulse_freq(r_spd);
        lv_textarea_set_text(ui_TextAreaM2Speed, String(f_spd).c_str());
    }else{
        // r/s
        if (last_index==1) {return;}
        last_index = 1;
        f_spd = String(lv_textarea_get_text(ui_TextAreaM2Speed)).toInt();
        r_spd = stepper_y.pulse_freq_to_rps(f_spd);
        lv_textarea_set_text(ui_TextAreaM2Speed, String(r_spd).c_str());
    }
}

void func_m1_cw_cb_pushed(lv_event_t * e){
 static int   f_spd = 0;
 static float r_spd = 0;
 if (lv_dropdown_get_selected(ui_DropdownM1SpeedType)==0){
    // Hz
    f_spd = String(lv_textarea_get_text(ui_TextAreaM1Speed)).toInt();
    stepper_x.run_freq(f_spd);
 }else{
    // rad/s
    r_spd = String(lv_textarea_get_text(ui_TextAreaM1Speed)).toFloat();
    stepper_x.run_rps(r_spd);
 }
}
void func_m1_cw_cb_released(lv_event_t * e){
    stepper_x.run_freq(0);
}
void func_m1_ccw_cb_pushed(lv_event_t * e){
    static int   f_spd = 0;
    static float r_spd = 0;
    if (lv_dropdown_get_selected(ui_DropdownM1SpeedType)==0){
        // Hz
        f_spd = String(lv_textarea_get_text(ui_TextAreaM1Speed)).toInt();
        stepper_x.run_freq(-f_spd);
    }else{
        // rad/s
        r_spd = String(lv_textarea_get_text(ui_TextAreaM1Speed)).toFloat();
        stepper_x.run_rps(-r_spd);
    }
}
void func_m1_ccw_cb_released(lv_event_t * e){
    stepper_x.run_freq(0);
}

void func_m2_cw_cb_pushed(lv_event_t * e){
 static int   f_spd = 0;
 static float r_spd = 0;
 if (lv_dropdown_get_selected(ui_DropdownM2SpeedType)==0){
    // Hz
    f_spd = String(lv_textarea_get_text(ui_TextAreaM2Speed)).toInt();
    stepper_y.run_freq(f_spd);
 }else{
    // rad/s
    r_spd = String(lv_textarea_get_text(ui_TextAreaM2Speed)).toFloat();
    stepper_y.run_rps(r_spd);
 }
}
void func_m2_cw_cb_released(lv_event_t * e){
    stepper_y.run_freq(0);
}
void func_m2_ccw_cb_pushed(lv_event_t * e){
 static int   f_spd = 0;
 static float r_spd = 0;
 if (lv_dropdown_get_selected(ui_DropdownM2SpeedType)==0){
    // Hz
    f_spd = String(lv_textarea_get_text(ui_TextAreaM2Speed)).toInt();
    stepper_y.run_freq(-f_spd);
 }else{
    // rad/s
    r_spd = String(lv_textarea_get_text(ui_TextAreaM2Speed)).toFloat();
    stepper_y.run_rps(-r_spd);
 }
}
void func_m2_ccw_cb_released(lv_event_t * e){
    stepper_y.run_freq(0);
}

void func_ButtonM1Enable(lv_event_t * e){
    stepper_x.enable();
}
void func_ButtonM1Disable(lv_event_t * e){
    stepper_x.disable();
}
void func_ButtonM2Enable(lv_event_t * e){
    stepper_y.enable();
}
void func_ButtonM2Disable(lv_event_t * e){
    stepper_y.disable();
}

void func_M1_speed_start(lv_event_t * e){
    static float r_spd = 0;
    static bool state = false;
    if (!state){
        r_spd = String(lv_textarea_get_text(ui_TextAreaM1Start)).toFloat();
        stepper_x.run_rps(r_spd);
        state = true;
        lv_obj_set_style_bg_color(ui_ButtonM1Start, lv_color_hex(0xE60B0B), LV_PART_MAIN | LV_STATE_DEFAULT);
        lv_label_set_text(ui_Label15, "Stop");
    }else{
        stepper_x.run_rps(0);
        state = false;
        lv_obj_set_style_bg_color(ui_ButtonM1Start, lv_color_hex(0x0D8723), LV_PART_MAIN | LV_STATE_DEFAULT);
        lv_label_set_text(ui_Label15, "Start");
    }
}

void func_M2_speed_start(lv_event_t * e){
    static float r_spd = 0;
    static bool state = false;
    if (!state){
        r_spd = String(lv_textarea_get_text(ui_TextAreaM2Start)).toFloat();
        stepper_y.run_rps(r_spd);
        state = true;
        lv_obj_set_style_bg_color(ui_ButtonM2Start, lv_color_hex(0xE60B0B), LV_PART_MAIN | LV_STATE_DEFAULT);
        lv_label_set_text(ui_Label16, "Stop");
    }else{
        stepper_y.run_rps(0);
        state = false;
        lv_obj_set_style_bg_color(ui_ButtonM2Start, lv_color_hex(0x0D8723), LV_PART_MAIN | LV_STATE_DEFAULT);
        lv_label_set_text(ui_Label16, "Start");
    }
}


// =========================步进参数设置====================================
void func_m1_ms_changed(lv_event_t * e)
{
	u_int16_t ms_select = ms_table[lv_dropdown_get_selected(ui_DropdownM1MicroSteps)];
    config_setting(stepper_x, String("ms ") + String(ms_select), motor0_setting_path);
}

void func_m1_angle_changed(lv_event_t * e)
{
	u_int16_t sa_select = ms_table[lv_dropdown_get_selected(ui_DropdownM1MicroSteps)];
    config_setting(stepper_x, String("sa ") + String(sa_select), motor0_setting_path);
}

void func_m2_ms_changed(lv_event_t * e)
{
	float ms_select = ms_table[lv_dropdown_get_selected(ui_DropdownM2MicroSteps)];
    config_setting(stepper_y, String("ms ") + String(ms_select), motor1_setting_path);
}

void func_m2_angle_changed(lv_event_t * e)
{
	float sa_select = sa_table[lv_dropdown_get_selected(ui_DropdownM2MicroSteps)];
    config_setting(stepper_y, String("sa ") + String(sa_select), motor1_setting_path);
}


// =========================WIFI连接按钮====================================
void func_wifi_disconnect_btn(lv_event_t * e){

}
void func_wifi_connect_btn(lv_event_t * e){

}


#endif